<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/22
 * Time: 13:38
 */

/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/19
 * Time: 17:07
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 *
 */
namespace app\admin\controller;
use app\admin\model\MessageTemplate;
use app\home\model\AmountLog;
use app\home\model\GoodsOrder;
use app\home\model\IntegralLog;
use app\home\model\PackageOrder;
use app\home\model\Recharge;
use app\home\model\User;
use app\home\model\UserAddress;
use app\home\model\UserCommission;
use app\home\model\UserCoupon;
use app\home\model\UserPackage;
use app\merchant\model\PayAmount;
use app\merchant\model\UserConsumption;
use app\Request;
use app\services\wechat\Offiaccount;
use app\home\model\Config;
use think\Exception;


class Order
{
    public function goodsOrderList(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if ($request->staff_account['store_id'] > 0) {
            $where[] = ['store_id', '=', $request->staff_account['store_id']];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        }
        if (isset($param['goods_name']) && !empty($param['goods_name'])) {
            $where[] = ['goods_name', 'like', '%' . $param['goods_name'] . '%'];
        }
        if (isset($param['sn_order']) && !empty($param['sn_order'])) {
            $where[] = ['sn_order', 'like', '%' . $param['sn_order'] . '%'];
        }

        if (isset($param['phone']) && !empty($param['phone'])) {
            $userModel = new User();
            $userInfo = $userModel->where(['phone' => $param['phone']])->find();
            if ($userInfo) {
                $where[] = ['user_id', '=', $userInfo['id']];
            } else {
                return adminSuccess('用户不存在', ['list' => [], 'count' => 0]);
            }
        }

        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $userModel = new User();
            $userInfo = $userModel->where([['nickname', 'like', '%' . $param['nickname'] . '%']])->select()->toArray();
            if ($userInfo) {
                $uids = array_column($userInfo, 'id');
                $where[] = ['user_id', 'in', $uids];
            } else {
                return adminSuccess('用户不存在', ['list' => [], 'count' => 0]);
            }
        }


        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['create_time', '<=', strtotime($param['end_time'])];
        }
        $goodsOrderModel = new GoodsOrder();
        if ($where) {
            $list = $goodsOrderModel
                ->where($where)
                ->limit($start, $limit)
                ->order('create_time', 'desc')
                ->select()->toArray();
            $count = $goodsOrderModel->where($where)->count();
        } else {
            $list = $goodsOrderModel
                ->limit($start, $limit)
                ->order('create_time', 'desc')
                ->select()->toArray();
            $count = $goodsOrderModel->where($where)->count();
        }

        if ($list) {
            $goodsId = array_column($list, 'goods_id');
            $uid = array_column($list, 'user_id');
            $userModel = new User();
            $userList = $userModel->where('id', 'in', $uid)->field('id,nickname,avatar,wachat_nickname,phone')->select()->toArray();
            $userById = array_column($userList, null, 'id');

            $goodsModel = new \app\merchant\model\Goods();
            $goodsList = $goodsModel->where('id', 'in', $goodsId)->field('id,name,host_img,title')->select()->toArray();
            $goodsListById = array_column($goodsList, null, 'id');

            $addressId = array_column($list, 'address_id');
            $addressListById = [];
            if ($addressId) {
                $userAddress = new UserAddress();
                $userAddressList = $userAddress->where('id', 'in', $addressId)->select()->toArray();
                if ($userAddressList) {
                    $addressListById = array_column($userAddressList, null, 'id');
                }

            }
            $storeId = array_column($list, 'store_id');
            $storeListById = [];
            if ($storeId) {
                $storeModel = new \app\merchant\model\Store();
                $storeList = $storeModel->where('id', 'in', $storeId)->select()->toArray();
                if ($storeList) {
                    $storeListById = array_column($storeList, null, 'id');
                }
            }

            foreach ($list as $key => $value) {
                $list[$key]['goods_name'] = $goodsListById[$value['goods_id']]['name'];
                $list[$key]['title'] = $goodsListById[$value['goods_id']]['title'];
                $list[$key]['host_img'] = $goodsListById[$value['goods_id']]['host_img'];
                $list[$key]['nickname'] = $userById[$value['user_id']]['nickname'];
                $list[$key]['avatar'] = $userById[$value['user_id']]['avatar'];
                $list[$key]['wachat_nickname'] = $userById[$value['user_id']]['wachat_nickname'];
                $list[$key]['phone'] = $userById[$value['user_id']]['phone'];
                if (array_key_exists($value['address_id'], $addressListById)) {
                    $list[$key]['city_id'] = $addressListById[$value['address_id']]['city_id'];
                    $list[$key]['county_id'] = $addressListById[$value['address_id']]['county_id'];
                    $list[$key]['province_id'] = $addressListById[$value['address_id']]['province_id'];
                    $list[$key]['province_name'] = $addressListById[$value['address_id']]['province_name'];
                    $list[$key]['city_name'] = $addressListById[$value['address_id']]['city_name'];
                    $list[$key]['county_name'] = $addressListById[$value['address_id']]['county_name'];
                    $list[$key]['phone'] = $addressListById[$value['address_id']]['phone'];
                    $list[$key]['name'] = $addressListById[$value['address_id']]['name'];
                    $list[$key]['address'] = $addressListById[$value['address_id']]['address'];
                } else {
                    $list[$key]['province_name'] = '';
                    $list[$key]['city_name'] = '';
                    $list[$key]['county_name'] = '';
                    $list[$key]['phone'] = '';
                    $list[$key]['name'] = '';
                    $list[$key]['address'] = '';
                    $list[$key]['city_id'] = '';
                    $list[$key]['county_id'] = '';
                    $list[$key]['province_id'] = '';
                }
                if (array_key_exists($value['store_id'], $storeListById)) {
                    $list[$key]['store_province_name'] = $storeListById[$value['store_id']]['province_name'];
                    $list[$key]['store_city_name'] = $storeListById[$value['store_id']]['city_name'];
                    $list[$key]['store_county_name'] = $storeListById[$value['store_id']]['county_name'];
                    $list[$key]['store_address'] = $storeListById[$value['store_id']]['address'];
                    $list[$key]['store_phone'] = $storeListById[$value['store_id']]['phone'];
                    $list[$key]['store_name'] = $storeListById[$value['store_id']]['name'];
                    $list[$key]['store_city_id'] = $storeListById[$value['store_id']]['city_id'];
                    $list[$key]['store_county_id'] = $storeListById[$value['store_id']]['county_id'];
                    $list[$key]['store_province_id'] = $storeListById[$value['store_id']]['province_id'];
                } else {
                    $list[$key]['store_province_name'] = '';
                    $list[$key]['store_city_name'] = '';
                    $list[$key]['store_city_name'] = '';
                    $list[$key]['store_address'] = '';
                    $list[$key]['store_phone'] = '';
                    $list[$key]['store_name'] = '';
                    $list[$key]['store_city_id'] = '';
                    $list[$key]['store_county_id'] = '';
                    $list[$key]['store_province_id'] = '';
                }
            }
        }
        return adminSuccess('商城订单列表', ['list' => $list, 'count' => $count]);
    }

    public function goodsOrderInfo(Request $request)
    {
        $param = $request->param();
        $goodsOrderModel = new GoodsOrder();
        $info = $goodsOrderModel->where(['id' => $param]['id'])->find();
        if ($info['address_id']) {
            $addressModel = new  UserAddress();
            $addressInfo = $addressModel->where(['id' => $info['address_id']])->find();
            $info['address_province_name'] = $addressInfo['province_name'];
            $info['address_city_name'] = $addressInfo['city_name'];
            $info['address_county_name'] = $addressInfo['county_name'];
            $info['address_address'] = $addressInfo['address'];
            $info['address_phone'] = $addressInfo['phone'];
            $info['address_name'] = $addressInfo['name'];
        } else {
            $info['address_province_name'] = '';
            $info['address_city_name'] = '';
            $info['address_county_name'] = '';
            $info['address_address'] = '';
            $info['address_phone'] = '';
            $info['address_name'] = '';
        }
        if ($info['coupon_id']) {
            $couponModel = new \app\home\model\Coupon();
            $couponInfo = $couponModel->where(['id' => $info['coupon_id']])->find();
            $info['coupon_name'] = $couponInfo['name'];
            $info['trigger_amount'] = $couponInfo['trigger_amount'];
            $info['discount_intensity'] = $couponInfo['discount_intensity'];
        } else {
            $info['coupon_name'] = '';
            $info['trigger_amount'] = '';
            $info['discount_intensity'] = '';
        }
        if ($info['store_id']) {
            $storeModel = new \app\merchant\model\Store();
            $storeInfo = $storeModel->where(['id' => $info['store_id']])->find();
            $info['store_province_name'] = $storeInfo['province_name'];
            $info['store_city_name'] = $storeInfo['city_name'];
            $info['store_county_name'] = $storeInfo['county_name'];
            $info['store_address'] = $storeInfo['address'];
            $info['store_phone'] = $storeInfo['phone'];
            $info['store_name'] = $storeInfo['name'];
        } else {
            $info['store_province_name'] = '';
            $info['store_city_name'] = '';
            $info['store_county_name'] = '';
            $info['store_address'] = '';
            $info['store_phone'] = '';
            $info['store_name'] = '';
        }
        $goodsModel = new \app\merchant\model\Goods();
        $goodsInfo = $goodsModel->where(['id' => $info['goods_id']])->find();
        $info['goods_desc'] = $goodsInfo['desc'];
        $info['goods_price'] = $goodsInfo['price'];
        $info['title'] = $goodsInfo['title'];
        return adminSuccess('订单详情', $info);
    }

    public function packageOrderList(Request $request)
    {
        $packageOrderModel = new PackageOrder();
        $param = $request->param();
        $limit = 10;
        $start = 0;
        $where = [];
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['po.status', '=', $param['status']];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['u.phone|u.wachat_nickname', 'like', '%' . $param['name'] . '%'];
        }
        if (isset($param['package_name']) && !empty($param['package_name'])) {
            $where[] = ['p.name', 'like', '%' . $param['package_name'] . '%'];
        }
        if (isset($param['order_sn']) && !empty($param['order_sn'])) {
            $where[] = ['po.order_sn', 'like', '%' . $param['order_sn'] . '%'];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['po.create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['po.create_time', '<=', strtotime($param['end_time'])];
        }
        $list = $packageOrderModel->alias('po')
            ->leftJoin('user u', 'po.uid = u.id')
            ->leftJoin('package p', 'po.package_id = p.id')
            ->order('po.create_time', 'desc')
            ->field('po.*,p.name  ,p.desc,p.logo, p.style,p.sales_amount,p.sales_volume, u.nickname,wachat_nickname,p.name')
            ->where($where)->limit($start, $limit)->select()->toArray();
        $count = $packageOrderModel->alias('po')
            ->leftJoin('user u', 'po.uid = u.id')
            ->leftJoin('package p', 'po.package_id = p.id')
            ->where($where)->count();

        if ($list) {
            $orderId = array_column($list, 'id');
            $packageUser = new UserPackage();
            $packageUserList = $packageUser->where('order_id', 'in', $orderId)->select()->toArray();
            $orderByPackage = array_column($packageUserList, null, 'order_id');
            foreach ($list as $key => $value) {
                if (array_key_exists($value['id'], $orderByPackage)) {
                    $list[$key]['num'] = $orderByPackage[$value['id']]['num'];
                    $list[$key]['use_num'] = $orderByPackage[$value['id']]['total_num'] - $orderByPackage[$value['id']]['num'];

                } else {
                    $list[$key]['num'] = 0;
                    $list[$key]['use_num'] = 0;
                }
            }

        }

        return adminSuccess('套餐卡订单列表', ['list' => $list, 'count' => $count]);
    }

    public function rechargeOrderList(Request $request)
    {
        $param = $request->param();
        $rechargeModel = new Recharge();
        $limit = 10;
        $start = 0;
        $where = [];
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['r.status', '=', $param['status']];
        } else {
            $where[] = ['r.status', 'in', [1, 2, 3]];
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['r.uid', '=', $param['uid']];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['u.phone|u.wachat_nickname|nickname', 'like', '%' . $param['name'] . '%'];
        }
        if (isset($param['phone']) && !empty($param['phone'])) {
            $where[] = ['u.phone', '=', $param['name']];
        }
        if (isset($param['nickname']) && !empty($param['nickname'])) {
            $where[] = ['u.wachat_nickname|nickname', 'like', '%' . $param['nickname'] . '%'];
        }
        if (isset($param['sn_order']) && !empty($param['sn_order'])) {
            $where[] = ['r.sn_order', '=', $param['sn_order']];
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['r.create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['edn_time']) && !empty($param['edn_time'])) {
            $where[] = ['r.create_time', '<=', strtotime($param['edn_time'])];
        }
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $list = $rechargeModel->alias('r')
            ->leftJoin('user u', 'r.uid = u.id')
            ->order('r.create_time', 'desc')
            ->field('r.* ,u.phone,u.wachat_nickname,u.nickname')
            ->where($where)->limit($start, $limit)->select()->toArray();
        $count = $rechargeModel->alias('r')
            ->leftJoin('user u', 'r.uid = u.id')->where($where)->count();
        return adminSuccess('充值列表', ['list' => $list, 'count' => $count]);
    }

    public function upNum(Request $request)
    {
        $param = $request->param();
        $userPackage = new \app\merchant\model\UserPackage();
        $userPackage->where(['order_id' => $param['id']])
            ->inc('num', $param['num'])
            ->inc('total_num', $param['num'])
            ->update();
        return adminSuccess('修改成功');
    }

    public function express(Request $request)
    {
        $param = $request->param();
        $orderModel = new GoodsOrder();
        $orderModel->where(['id' => $param['id']])->update([
            'express_name' => $param['express_name'],
            'express_phone' => $param['express_phone'],
            'status' => 4
        ]);
        return adminSuccess('修改成功');
    }

    public function amountLog(Request $request)
    {
        $amountLog = new AmountLog();
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where = [];
        if (isset($param['pay_method']) && !empty($param['pay_method'])) {
            $where[] = ['pay_method', '=', $param['pay_method']];
        }
        if (isset($param['pay_type']) && !empty($param['pay_type'])) {
            $where[] = ['pay_type', '=', $param['pay_type']];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $where[] = ['u.wachat_nickname|u.phone|nickname', 'like', '%', $param['name'] . '%'];
        }
        if (isset($param['uid']) && !empty($param['uid'])) {
            $where[] = ['u.uid', '=', $param['name']];
        }
        if ($request->staff_account['role_type'] == 3) {
            $where[] = ['a.store_id', '=', $request->staff_account['store_id']];

        } elseif ($request->staff_account['role_type'] == 2) {

            $where[] = ['a.staff_id', '=', $request->staff_account['id']];
        }
        $amountList = $amountLog
            ->alias('a')
            ->leftJoin('user u', 'a.uid = u.id')
            ->leftJoin('staff_account sa', 'sa.id = a.staff_id')
            ->field('a.*,u.phone,u.nickname,u.wachat_nickname,sa.name')
            ->where($where)
            ->order('a.create_time', 'desc')
            ->limit($start, $limit)
            ->select()->toArray();
        $count = $amountLog->alias('a')
            ->leftJoin('staff_account sa', 'sa.id = a.staff_id')
            ->leftJoin('user u', 'a.uid = u.id')
            ->where($where)
            ->count();
        return adminSuccess('消费记录', ['list' => $amountList, 'count' => $count]);
    }

    public function rechargeOrder(Request $request)
    {
        $param = $request->param();
        if (empty($param['id'])){
            return  adminError('请选择用户');
        }
        $data = [
            'type' => $param['type'],
            'uid' => $param['id'],
            'amount' => $param['amount'],
            'create_time' => time(),
            'sn_order' => getOrderNo('re_'),
            'update_time' => time(),
            'total_amount' => $param['amount'],
            'give_amount' => 0,
            'staff_id' => $request->staff_account['id'],
            'store_id' => $request->staff_account['store_id'],
        ];
        $payAmount = new PayAmount();
        $payAmountConfig = $payAmount
            ->where('amount', '<=', $param['amount'])
            ->where(['status' => 1])
            ->order('amount', 'desc')
            ->find();
        if ($payAmountConfig) {
            $data['total_amount'] = $param['amount'] + $payAmountConfig['give_amount'];
            $data['give_amount'] = $payAmountConfig['give_amount'];
        }
        $recharge = new  Recharge();
        if ($param['type'] == 6) {
            $pay_type = Config::getConfigValue('pay_type');
            if ($pay_type == 1) {
                $data['pay_destination'] = 2;
            } else {
                $data['pay_destination'] = 3;
            }

        }
        $recharge->insert($data);
        $orderId = $recharge->getLastInsID();
        if ($param['type'] == 6) {
            $data['reality_amount'] = $param['amount'];
            $Offiaccount = new Offiaccount();
            $wechatInfo = $Offiaccount->paymentCode($data, $request->ip(), $param['auth_code']);

            if ($wechatInfo['return_code'] == 'SUCCESS') {
                if ($wechatInfo['result_code'] == 'SUCCESS') {
                    $recharge->where(['id' => $orderId])->update(['pay_status' => 1, 'pay_time' => time()]);
                    return adminSuccess('等待查询订单状态');

                } else {
                    return adminError($wechatInfo['err_code_des']);
                }
            } else {
                return adminError($wechatInfo['return_msg']);
            }

        } else if ($param['type'] == 7) {
            $data['reality_amount'] = $param['amount'];
            $Offiaccount = new \app\services\alipay\Offiaccount();
            $aliPayInfo = $Offiaccount->paymentCode($param['auth_code'], $data);
            if ($aliPayInfo['code'] != '1') {
                return adminError('失败');
            } else {
                $recharge->where(['id' => $orderId])->update(['pay_status' => 1, 'pay_time' => time()]);
                return adminSuccess('等待查询订单状态');
            }
        }
        switch ($param['type']) {
            case 2:
                $data['status'] = 3;
                $payMethod = 1;
                $pay_type = 2;
                $operate_type = 2;
                break;
            case 3:
                $data['status'] = 3;
                $payMethod = 2;;
                $pay_type = 2;
                $operate_type = 3;
                break;
            case 4:
                $data['status'] = 3;
                $payMethod = 3;
                $pay_type = 2;
                $operate_type = 4;
                break;
            case 5:
                $data['status'] = 3;
                $payMethod = 5;
                $pay_type = 2;
                $operate_type = 5;
                break;


        }
        $AmountLogData = [
            'uid' => $param['id'],
            'amount' => $data['amount'],
            'create_time' => time(),
            'pay_type' => $pay_type,
            'operate_type' => $operate_type,
            'pay_method' => $payMethod,
            'order_id' => $orderId,
            'order_sn' => $data['sn_order'],
            'ratio' => 1,
            'type' => 1,
            'staff_id' => $request->staff_account['id'],
            'store_id' => $request->staff_account['store_id'],
            'give_amount' => $data['give_amount'],
        ];
        $amountLogModel = new AmountLog();
        $amountLogModel->insert($AmountLogData); // 余
        if ($request->staff_account['store_id']> 0){
            $storeModel = new \app\merchant\model\Store();
            $storeModel->where(['id' => $request->staff_account['store_id']])->inc('recharge_amount',$data['amount'])->update();
        }
        $recharge->where(['id' => $orderId])->update(['status' => 3]);
        $userModel = new User();
        $userModel->where(['id' => $param['id']])
            ->inc('balance', $data['total_amount'])
            ->inc('recharge_amount', $data['amount'])
            ->update();
        return adminSuccess('操作成功');

    }

    public function createGoodsOrder(Request $request)
    {
        $param = $request->param();
        $userModel = new User();
        if ($param['pay_way'] == 1) {
            $userInfo = $userModel->where(['id' => $param['uid'], 'random_code' => $param['random_code']])->find();
            if (empty($userInfo)) {
                return adminError('用户付款码有误');
            }
        } else {
            $userInfo = $userModel->where(['id' => $param['uid']])->find();
            if (empty($userInfo)) {
                return adminError('用户不存在');
            }
        }
        $data = [
            'uid' => $param['uid'],
            'staff_id' => $request->staff_account['id'],
            'store_id' => $request->staff_account['store_id'],
            'amount' => $param['amount'],
            'pay_type' => $param['pay_way'],
            'status' => 1,
            'sn_order' => getOrderNo('co'),
            'create_time' => time(),
            'pay_time' => time(),
            'pay_status' => 0,
            'get_integral' => 0,
            'get_integral_ratio' => 0,
            'original_price' => $param['amount'],
        ];
        $levelModel = new \app\merchant\model\Level();
        $levelInfo = $levelModel->where(['id' => $userInfo['level_id']])->find();

        if ($levelInfo['shopping_preferential'] > 0) { // 针对商城全局的折扣
            $data['amount'] = bcdiv(bcmul($param['amount'], $levelInfo['shopping_preferential'], 2), 100, 2);
            $data['discount_ratio'] = $levelInfo['shopping_preferential'];
            $data['discount_type'] = 2;
        } else {
            if ($levelInfo['preferential'] > 0) {  // 全局的折扣
                $data['amount'] = bcdiv(bcmul($param['amount'], $levelInfo['preferential'], 2), 100, 2);
                $data['discount_ratio'] = $levelInfo['preferential'];
                $data['discount_type'] = 3;
            }
        }
        if ($param['pay_way'] == 7) {
            $pay_type = Config::getConfigValue('pay_type');
            if ($pay_type == 1) {
                $data['pay_destination'] = 2;
            } else {
                $data['pay_destination'] = 3;
            }

        }
        $consumptionIntegralRatio = Config::getConfigValue('consumption_integral_ratio');
        $integral = bcmul($consumptionIntegralRatio, $data['amount'], 2);
        if ($userInfo['birthday']) {
            $dateTime = date('Y-m-d', time());
            if ($userInfo['birthday'] == $dateTime) {
                $integral = bcmul($integral, 2, 2);
            }
        }
        $data['get_integral'] = $integral;
        $data['get_integral_ratio'] = $consumptionIntegralRatio;
        $userConsumptionModel = new UserConsumption();
        if ($param['pay_way'] == 1) {
            if ($userInfo['balance'] < $data['amount']) {
                return adminError('用户余额不足');
            }
        }
        $userConsumptionModel->insert($data);
        $orderId = $userConsumptionModel->getLastInsID();
        try {
            if (in_array($param['pay_way'], [7, 8]) && $data['amount'] > 0) {
                $data['reality_amount'] = $data['amount'];
                if ($param['pay_way'] == 7) {
                    $Offiaccount = new Offiaccount();
                    $wechatInfo = $Offiaccount->paymentCode($data, $request->ip(), $param['auth_code']);
                    if ($wechatInfo['return_code'] == 'SUCCESS') {
                        if ($wechatInfo['result_code'] == 'SUCCESS') {
                            $userConsumptionModel->where(['id' => $orderId])->update(['pay_status' => 1, 'pay_time' => time()]);
                            return adminSuccess('等待查询订单状态');

                        } else {
                            return adminError($wechatInfo['err_code_des']);
                        }
                    } else {
                        return adminError($wechatInfo['return_msg']);
                    }
                } else {
                    $Offiaccount = new \app\services\alipay\Offiaccount();
                    $aliPayInfo = $Offiaccount->paymentCode($param['auth_code'], $data);
                    if ($aliPayInfo['code'] != '1') {
                        return adminError('支付失败');
                    } else {
                        $userConsumptionModel->where(['id' => $orderId])->update(['pay_status' => 1, 'pay_time' => time()]);
                        return adminSuccess('等待查询订单状态');
                    }
                }
            }
            $userModel->startTrans();
            if ($param['pay_way'] == 1) {
                $userModel->where(['id' => $param['uid']])->dec('balance', $data['amount'])->update();
            }
            $userModel->where(['id' => $userInfo['id']])
                ->inc('consumption_amount', $data['amount'])
                ->inc('integral', $integral)
                ->inc('surplus_integral', $integral)
                ->update();
            $userModel->updateUserLevel($userInfo['id'], bcadd($userInfo['consumption_amount'], $data['amount'], 2));
            if ($integral > 0) {
                $integralLogModel = new IntegralLog();
                $integralLogData = [ // 积分变化
                    'num' => $integral,
                    'deduction_ratio' => $consumptionIntegralRatio,
                    'type' => 1,
                    'mode_type' => 8,
                    'order_id' => $orderId,
                    'create_time' => time(),
                    'uid' => $userInfo['id'],
                ];
                $integralLogModel->insert($integralLogData);
            }
            $distribution_level = Config::getConfigValue('distribution_level');
            $firstCommissionData = [];
            $secondCommissionData = [];
            if ($distribution_level > 0) {
                if ($userInfo['pid'] > 0) {
                    $first_commission = Config::getConfigValue('first_commission');
                    if ($first_commission > 0) {
                        $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                        $userCommissionModel = new UserCommission();
                        $firstCommissionData = [
                            'trigger_uid' => $userInfo['id'],
                            'receive_uid' => $userInfo['pid'],
                            'level' => 1,
                            'amount' => bcdiv(bcmul($data['amount'], $first_commission, 2), 100, 2),
                            'ratio' => $first_commission,
                            'order_id' => $orderId,
                            'create_time' => time(),
                            'type' => 1,
                        ];
                        $userCommissionModel->insert($firstCommissionData);
                        $userModel->where(['id' => $userInfo['pid']])
                            ->inc('total_commission', bcdiv(bcmul($first_commission, $data['amount'], 2), 100, 2))
                            ->inc('surplus_commission', bcdiv(bcmul($first_commission, $data['amount'], 2), 100, 2))
                            ->update();
                    }
                    if ($distribution_level >= 2) {
                        $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                        $second_commission = Config::getConfigValue('second_commission');

                        if ($second_commission > 0 && $pUserInfo['pid'] > 0) {
                            $userCommissionModel = new UserCommission();
                            $secondCommissionData = [
                                'trigger_uid' => $userInfo['id'],
                                'receive_uid' => $pUserInfo['pid'],
                                'level' => 2,
                                'amount' => bcdiv(bcmul($data['amount'], $second_commission, 2), 100, 2),
                                'ratio' => $second_commission,
                                'order_id' => $orderId,
                                'create_time' => time(),
                                'type' => 1,
                            ];
                            $userCommissionModel->insert($secondCommissionData);
                            $userModel->where(['id' => $pUserInfo['pid']])
                                ->inc('total_commission', bcdiv(bcmul($second_commission, $data['amount'], 2), 100, 2))
                                ->inc('surplus_commission', bcdiv(bcmul($second_commission, $data['amount'], 2), 100, 2))
                                ->update();
                        }
                    }
                }
            }
            $amountLogModel = new  AmountLog(); // 支付记录
            switch ($param['pay_way']) {
                case 1 :   // 余额
                    $operate_type = 21;
                    $pay_type = 4;
                    $pay_method = 4;
                    break;
                case 3 :   // 微信
                    $operate_type = 22;
                    $pay_type = 2;
                    $pay_method = 1;
                    break;
                case 4 :   // 支付宝
                    $operate_type = 23;
                    $pay_type = 2;
                    $pay_method = 2;
                    break;
                case 5 :   // 现金
                    $operate_type = 24;
                    $pay_type = 2;
                    $pay_method = 3;
                    break;
                case 6 :   // pos
                    $operate_type = 25;
                    $pay_type = 2;
                    $pay_method = 5;
                    break;
                case 7 :   // pos
                    $operate_type = 26;
                    $pay_type = 1;
                    $pay_method = 2;
                    break;
                case 8 :   // pos
                    $operate_type = 27;
                    $pay_type = 1;
                    $pay_method = 1;
                    break;
            }
            $amountLogData = [
                'uid' => $userInfo['id'],
                'amount' => $data['amount'],
                'create_time' => time(),
                'order_id' => $orderId,
                'pay_method' => $pay_method,
                'operate_type' => $operate_type,
                'pay_type' => $pay_type,
                'ratio' => 1,
                'type' => 2,
                'order_sn' => $data['sn_order'],
                'staff_id'  => $request->staff_account['id'],
                'store_id' => $request->staff_account['store_id'],
            ];
            $amountLogModel->insert($amountLogData);
            $userConsumptionModel->where(['id' => $orderId])->update(['pay_status' => 2, 'pay_time' => time(), 'update_time' => time()]);
            if ($request->staff_account['store_id']> 0){
                $storeModel = new \app\merchant\model\Store();
                $storeModel->where(['id' => $request->staff_account['store_id']])->inc('recharge_amount',$data['amount'])->update();
            }
            $userModel->commit();
            $messageModel = new MessageTemplate();
            if ($firstCommissionData) { // 一级分佣
                $messageModel->sendMessage($pUserInfo['openid'], [
                    'thing2' => ['value' => '直推佣金'],
                    'amount8' => ['value' => $firstCommissionData['amount']],
                    'amount6' => ['value' => bcadd($pUserInfo['surplus_commission'], $firstCommissionData['amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
            }
            if ($secondCommissionData) { // 一级分佣
                $messageModel->sendMessage($ppUserInfo['openid'], [
                    'thing2' => ['value' => '间推佣金'],
                    'amount8' => ['value' => $secondCommissionData['amount']],
                    'amount6' => ['value' => bcadd($ppUserInfo['surplus_commission'], $secondCommissionData['amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')],
                ], 'commission_add'); //
            }
            if ($param['pay_way'] == 1) {
                $messageModel->sendMessage($userInfo['openid'], [
                    'thing6' => ['value' => '消费扣款'],
                    'amount2' => ['value' => $data['amount']],
                    'amount4' => ['value' => bcsub($userInfo['balance'], $data['amount'], 2)],
                    'time1' => ['value' => date('Y-m-d H:i:s')]
                ], 'balance_sub'); // 余额变动
                if ($userInfo['phone']) {
                    $messageModel->sendAliMessage($userInfo['phone'], 'balance_sub', [
                        'platform' => Config::getConfigValue('system_name'),
                        'name' => '商品',
                        'money' => $data['amount'],
                    ]);;
                }
            }
            if ($integral > 0) {  // 添加积分
                $messageModel->sendMessage($userInfo['openid'], [
                    'thing2' => ['value' => '积分'],
                    'amount8' => ['value' => $integral . '分'],
                    'amount6' => ['value' => bcadd($userInfo['surplus_integral'], $integral, 2) . '分'],
                    'time4' => ['value' => date('Y-m-d H:i')]
                ], 'integral_add'); //
            }
        } catch (\Exception $exception) {
            $userModel->rollback();
            return adminError($exception->getMessage() . $exception->getLine());
        }

        return success('购买成功');

    }

    public function createPackageOrder(Request $request)
    {
        $param = $request->param();
        $packageModel = new \app\home\model\Package();
        $packageInfo = $packageModel->where(['id' => $param['id']])->find();
        if (empty($packageInfo)) {
            return adminError('套餐卡不存在');
        }
        $data = [
            'uid' => $param['uid'],
            'order_sn' => getOrderNo('pa_'),
            'package_id' => $param['id'],
            'price' => $packageInfo['price'],
            'create_time' => time(),
            'status' => 1,
            'original_price' => $packageInfo['price'],
            'pay_type' => $param['pay_way'],
            'staff_id' => $request->staff_account['id'],
            'store_id' => $request->staff_account['store_id'],
            'get_integral' => 0,
            'get_integral_ratio' => 0,
            'number' => $packageInfo['number'],
            'give_number' => $packageInfo['give_number'],
        ];
        $userModel = new User();

        if (in_array($param['pay_way'], [7, 8])) {
            if ($param['pay_way'] == 7) {
                $pay_type = Config::getConfigValue('pay_type');
                if ($pay_type == 1) {
                    $data['pay_destination'] = 2;
                } else {
                    $data['pay_destination'] = 3;
                }
            }
            $userInfo = $userModel->where(['id' => $param['uid']])->find();
        } else {
            $userInfo = $userModel->where(['id' => $param['uid'], 'random_code' => $param['random_code']])->find();
        }
        if (empty($userInfo)) {
            return adminError('用户不存在');
        }
        $levelModel = new \app\merchant\model\Level();
        $levelInfo = $levelModel->where(['id' => $userInfo['level_id']])->find();
        if ($levelInfo['package_preferential'] > 0) { // 针对商城全局的折扣
            $data['price'] = bcdiv(bcmul($packageInfo['price'], $levelInfo['package_preferential'], 2), 100, 2);
            $data['discount_ratio'] = $levelInfo['package_preferential'];
            $data['discount_type'] = 2;
        } else {
            if ($levelInfo['preferential'] > 0) {  // 全局的折扣
                $data['price'] = bcdiv(bcmul($data['price'], $levelInfo['preferential'], 2), 100, 2);
                $data['discount_ratio'] = $levelInfo['preferential'];
                $data['discount_type'] = 3;
            }
        }
        $packageOrderModel = new PackageOrder();
        $consumptionIntegralRatio = Config::getConfigValue('consumption_integral_ratio');
        $integral = bcmul($consumptionIntegralRatio, $data['price'], 2);
        if ($userInfo['birthday']) {
            $dateTime = date('Y-m-d', time());
            if ($userInfo['birthday'] == $dateTime) {
                $integral = bcmul($integral, 2, 2);
            }
        }
        $data['get_integral'] = $integral;
        $data['get_integral_ratio'] = $consumptionIntegralRatio;

        $packageOrderModel->insert($data);
        $orderId = $packageOrderModel->getLastInsID();
        if (in_array($param['pay_way'], [7, 8])) {
            $data['reality_amount'] = $data['price'];
            $data['sn_order'] = $data['order_sn'];
            if ($param['pay_way'] == 7) {
                $Offiaccount = new Offiaccount();
                $wechatInfo = $Offiaccount->paymentCode($data, $request->ip(), $param['auth_code']);
                if ($wechatInfo['return_code'] == 'SUCCESS') {
                    if ($wechatInfo['result_code'] == 'SUCCESS') {
                        $packageOrderModel->where(['id' => $orderId])->update(['pay_status' => 1, 'pay_time' => time()]);
                        return success('等待查询订单状态');

                    } else {
                        return adminError($wechatInfo['err_code_des']);
                    }
                } else {
                    return adminError($wechatInfo['return_msg']);
                }
            } else {
                $Offiaccount = new \app\services\alipay\Offiaccount();
                $aliPayInfo = $Offiaccount->paymentCode($param['auth_code'], $data);
                if ($aliPayInfo['code'] != '1') {
                    return adminError('支付失败');
                } else {
                    $packageOrderModel->where(['id' => $orderId])->update(['pay_status' => 1, 'pay_time' => time()]);
                    return adminSuccess('等待查询订单状态');
                }
            }
        }
        switch ($param['pay_way']) {
            case 1:
                $status = 3;
                $payMethod = 4;
                $pay_type = 4;
                $payName = '余额支付';
                $operate_type = 11;
                break;
            case 3:
                $status = 3;
                $payMethod = 1;;
                $pay_type = 2;
                $payName = '微信';
                $operate_type = 12;
                break;
            case 4:
                $status = 3;
                $payMethod = 2;
                $pay_type = 2;
                $payName = '支付宝';
                $operate_type = 13;
                break;
            case 5:
                $status = 3;
                $payMethod = 3;
                $pay_type = 2;
                $payName = '现金';
                $operate_type = 14;
                break;
            case 6:
                $status = 3;
                $payMethod = 5;
                $pay_type = 2;
                $payName = '刷卡';
                $operate_type = 15;
                break;
            case 7:
                $status = 1;
                $payMethod = 1;
                $pay_type = 1;
                $payName = '微信';
                $operate_type = 16;
                break;
            case 8:
                $status = 1;
                $payMethod = 2;
                $pay_type = 1;
                $payName = '支付宝';
                $operate_type = 17;
                break;
        }
        $AmountLogData = [  // 金额扣除记录
            'uid' => $param['uid'],
            'amount' => $data['price'],
            'create_time' => time(),
            'operate_type' => $operate_type,
            'pay_type' => $pay_type,
            'pay_method' => $payMethod,
            'order_id' => $orderId,
            'ratio' => 1,
            'type' => 2,
            'staff_id' => $request->staff_account['id'],
            'store_id' => $request->staff_account['store_id'],
            'order_sn' => $data['order_sn'],
        ];
        try {
            if ($param['pay_way'] == 1) {
                if ($userInfo['balance'] < $data['price']) {
                    $userModel->rollback();
                    return adminError('余额不足');
                }
                $userModel->where(['id' => $userInfo['id']])->dec('balance', $data['price'])->update();
            }
            $userModel->startTrans();
            $amountLogModel = new AmountLog();
            $amountLogModel->insert($AmountLogData); // 余额支付 余额扣除
            if ($request->staff_account['store_id']> 0){
                $storeModel = new \app\merchant\model\Store();
                $storeModel->where(['id' => $request->staff_account['store_id']])->inc('package_amount',$data['price'])->update();
            }

            $integralLogModel = new IntegralLog();
            $consumptionIntegralRatio = Config::getConfigValue('consumption_integral_ratio');
            $userModel = new \app\home\model\User();
            $distribution_level = Config::getConfigValue('distribution_level');
            $firstCommissionData = [];
            $secondCommissionData = [];
            if ($distribution_level > 0) {
                if ($userInfo['pid'] > 0) {
                    $first_commission = Config::getConfigValue('first_commission');
                    $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                    if ($first_commission > 0) {

                        $userCommissionModel = new UserCommission();
                        $firstCommissionData = [
                            'trigger_uid' => $userInfo['id'],
                            'receive_uid' => $userInfo['pid'],
                            'level' => 1,
                            'amount' => bcdiv(bcmul($data['price'], $first_commission, 2), 100, 2),
                            'ratio' => $first_commission,
                            'order_id' => $orderId,
                            'create_time' => time(),
                            'type' => 2,
                        ];
                        $userCommissionModel->insert($firstCommissionData);
                        $userModel->where(['id' => $userInfo['pid']])
                            ->inc('total_commission', bcdiv(bcmul($first_commission, $data['price'], 2), 100, 2))
                            ->inc('surplus_commission', bcdiv(bcmul($first_commission, $data['price'], 2), 100, 2))
                            ->update();
                    }
                    if ($distribution_level >= 2) {

                        $second_commission = Config::getConfigValue('second_commission');
                        if ($pUserInfo['pid'] > 0 && $second_commission > 0) {
                            $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                            $userCommissionModel = new UserCommission();
                            $secondCommissionData = [
                                'trigger_uid' => $userInfo['id'],
                                'receive_uid' => $pUserInfo['pid'],
                                'level' => 2,
                                'amount' => bcdiv(bcmul($data['price'], $second_commission, 2), 100, 2),
                                'ratio' => $second_commission,
                                'order_id' => $orderId,
                                'create_time' => time(),
                                'type' => 2,
                            ];
                            $userCommissionModel->insert();
                            $userModel->where(['id' => $pUserInfo['pid']])
                                ->inc('total_commission', bcdiv(bcmul($second_commission, $data['price'], 2), 100, 2))
                                ->inc('surplus_commission', bcdiv(bcmul($second_commission, $data['price'], 2), 100, 2))
                                ->update();
                        }
                    }
                }
            }
            $userModel->where(['id' => $userInfo['id']])
                ->inc('consumption_amount', $data['price'])
                ->inc('package_num')
                ->inc('integral', $integral)
                ->inc('surplus_integral', $integral)
                ->update();
            $userModel->updateUserLevel($userInfo['id'], bcadd($userInfo['consumption_amount'], $data['price'], 2));
            $integralLogData = [ // 积分变化
                'num' => $integral,
                'deduction_ratio' => $consumptionIntegralRatio,
                'type' => 1,
                'mode_type' => 5,
                'order_id' => $orderId,
                'create_time' => time(),
                'uid' => $userInfo['id'],
            ];
            $integralLogModel->insert($integralLogData);
            $userPackageModel = new UserPackage();
            $userPackageData = [
                'package_id' => $param['id'],
                'uid' => $userInfo['id'],
                'num' => $packageInfo['number'] + $packageInfo['give_number'],
                'total_num' => $packageInfo['number'] + $packageInfo['give_number'],
                'create_time' => time(),
                'order_id' => $orderId,
            ];
            $userPackageModel->insert($userPackageData);
            $packageModel->where(['id' => $param['id']])->inc('sales_volume')->inc('sales_amount', $data['price'])->update();
            $packageOrderModel->where(['id' => $orderId])->update(['status' => $status]);
            $userModel->commit();
            $messageModel = new MessageTemplate();
            if ($param['pay_way'] == 1) {
                $messageModel->sendMessage($userInfo['openid'], [
                    'thing6' => ['value' => substr($packageInfo['name'], 0, 18)],
                    'amount2' => ['value' => $data['price']],
                    'amount4' => ['value' => bcsub($userInfo['balance'], $data['price'], 2)],
                    'time1' => ['value' => date('Y-m-d H:i:s')],
                ], 'balance_sub'); // 余额变动
                if ($userInfo['phone']) {
                    $messageModel->sendAliMessage($userInfo['phone'], 'balance_sub', [
                        'platform' => Config::getConfigValue('system_name'),
                        'name' => $packageInfo['name'],
                        'money' => $data['price'],
                    ]);;
                }
            }
            if ($firstCommissionData) { // 一级分佣
                $messageModel->sendMessage($pUserInfo['openid'], [
                    'thing2' => ['value' => '直推佣金'],
                    'amount8' => ['value' => $firstCommissionData['amount']],
                    'amount6' => ['value' => bcadd($pUserInfo['surplus_commission'], $firstCommissionData['amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
            }
            if ($secondCommissionData) { // 一级分佣
                $messageModel->sendMessage($ppUserInfo['openid'], [
                    'thing2' => ['value' => '间推佣金'],
                    'amount8' => ['value' => $secondCommissionData['amount']],
                    'amount6' => ['value' => bcadd($ppUserInfo['surplus_commission'], $secondCommissionData['amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')],
                ], 'commission_add'); //
            }
            if ($integral) {  // 积分变动
                $messageModel->sendMessage($userInfo['openid'], [
                    'thing2' => ['value' => '积分'],
                    'amount2' => ['value' => $integral . '分'],
                    'amount6' => ['value' => bcadd($userInfo['surplus_integral'], $integral, 2) . '分'],
                    'time4' => ['value' => date('Y-m-d H:i')],
                ], 'integral_add'); //
            }
            $messageModel->sendMessage($userInfo['openid'], [
                'thing2' => ['value' => $packageInfo['name']],
                'amount3' => ['value' => $packageInfo['price']],
                'thing9' => ['value' => date('Y-m-d  H:i:s')],

            ], 'buy_package'); // 购买套餐卡

        } catch (Exception $exception) {
            $userModel->rollback();
            return adminError($exception->getMessage());
        }
        return adminSuccess('购买成功');
    }

    public function withdrawalList(Request $request)
    {
        $param = $request->param();
        $withdrawalModel = new \app\home\model\Withdrawal();
        $where = [];
        if (isset($param['pay_mode']) && !empty($param['pay_mode'])) {
            $where['pay_mode'] = $param['pay_mode'];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $userWhere[] = ['phone|wachat_nickname|nickname', 'like', '%' . $param['name'] . '%'];
            $userModel = new User();
            $userArray = $userModel->where($userWhere)->select()->toArray();
            if ($userArray) {
                $where[] = ['uid', 'in', array_column($userArray, 'id')];
            } else {
                return adminSuccess('提现列表', ['list' => [], 'count' => 0]);
            }
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['create_time', '<=', strtotime($param['end_time'])];
        }
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $list = $withdrawalModel->where($where)->limit($start, $limit)->order('create_time', 'desc')->select()->toArray();
        if ($list) {
            $uidArray = array_column($list, 'uid');
            $userModel = new User();
            $userList = $userModel->where('id', 'in', $uidArray)
                ->field('id,phone,nickname,wachat_nickname,avatar')
                ->select()->toArray();
            $userListById = array_column($userList, null, 'id');
            foreach ($list as $key => $value) {
                $list[$key]['phone'] = $userListById[$value['uid']]['phone'];
                $list[$key]['nickname'] = $userListById[$value['uid']]['nickname'];
                $list[$key]['wachat_nickname'] = $userListById[$value['uid']]['wachat_nickname'];
                $list[$key]['avatar'] = $userListById[$value['uid']]['avatar'];
            }

        }
        $count = $withdrawalModel->where($where)->count();
        return adminSuccess('提现列表', ['list' => $list, 'count' => $count]);
    }

    public function withdrawalReject(Request $request)
    {
        $param = $request->param();
        $withdrawalModel = new \app\home\model\Withdrawal();
        $withdrawalInfo = $withdrawalModel->where(['id' => $param['id']])->find();
        if ($withdrawalInfo['status'] != 1) {
            return adminError('订单状态有误');
        }
        $userModel = new User();
        try {
            $withdrawalModel->startTrans();
            $withdrawalModel->where(['id' => $param['id']])->update(['status' => 4, 'remark' => $param['remark']]);
            $commission = bcdiv($withdrawalInfo['amount'], $withdrawalInfo['ratio'], 2);
            $userModel->where(['id' => $withdrawalInfo['uid']])->inc('surplus_commission', $commission)->update();
            $withdrawalModel->commit();

            $userModel = new User();
            $userInfo = $userModel->where(['id' => $withdrawalInfo['uid']])->find();
            $messageModel = new MessageTemplate();
            /*$messageModel->sendMessage($userInfo['openid'], [
                'time1' => ['value' => date('Y-m-d H:i:s', $withdrawalInfo['create_time'])],
                'amount2' => ['value' => $withdrawalInfo['amount']],
                'const3' => ['value' => $withdrawalInfo['remark']],
            ], 'withdrawal_fail');*/ //
        } catch (Exception $exception) {
            $withdrawalModel->rollback();
            return adminError($exception->getMessage());
        }
        return adminSuccess('操作成功');

    }

    public function amountLogInfo(Request $request)
    {
        $param = $request->param();
        $amountLog = new AmountLog();
        $amountLogInfo = $amountLog->where(['id' => $param['id']])->find();

        if (in_array($amountLogInfo['operate_type'], [1, 2, 3, 4, 5, 6, 7])) {
            $rechargeModel = new Recharge();
            $amountLogInfo['recharge_order'] = $rechargeModel->where(['id' => $amountLogInfo['order_id']])->find();

        } elseif (in_array($amountLogInfo['operate_type'], [8, 9, 18, 19])) {
            $goodsOrderModel = new GoodsOrder();
            $amountLogInfo['goods_order'] = $goodsOrderModel->where(['id' => $amountLogInfo['order_id']])->find();
            $goodsModel = new \app\merchant\model\Goods();
            $goodsInfo = $goodsModel->where(['id' => $amountLogInfo['goods_order']['goods_id']])->find();
            $amountLogInfo['goods_order']['title'] = $goodsInfo['title'];
            $amountLogInfo['goods_order']['host_img'] = $goodsInfo['host_img'];
            $amountLogInfo['goods_order']['desc'] = $goodsInfo['desc'];

        } elseif (in_array($amountLogInfo['operate_type'], [10, 11, 12, 13, 14, 15, 16, 17])) {
            $packageOrderModel = new PackageOrder();
            $amountLogInfo['package_order'] = $packageOrderModel->where(['id' => $amountLogInfo['order_id']])->find();
            $packageModel = new \app\merchant\model\Package();
            $packageInfo = $packageModel->where(['id' => $amountLogInfo['package_order']['package_id']])->find();
            $amountLogInfo['package_order']['name'] = $packageInfo['name'];
            $amountLogInfo['package_order']['style'] = $packageInfo['style'];
            $amountLogInfo['package_order']['logo'] = $packageInfo['logo'];
            $amountLogInfo['package_order']['desc'] = $packageInfo['desc'];
            $amountLogInfo['package_order']['sales_volume'] = $packageInfo['sales_volume'];
            $amountLogInfo['package_order']['sales_amount'] = $packageInfo['sales_amount'];
        } elseif (in_array($amountLogInfo['operate_type'], [21, 22, 23, 24, 24, 26, 27, 28])) {

            $amountLogInfo['operate_name'] = '收银台扣款';
        } else {
            $amountLogInfo['operate_name'] = '手动操作';
        }
        return adminSuccess('订单详情', $amountLogInfo);

    }

    public function upAddress(Request $request)
    {
        $param = $request->param();
        $goodsOrderModel = new GoodsOrder();
        $info = $goodsOrderModel->where(['id' => $param['id']])->find();
        $userAddressModel = new UserAddress();
        $data = [
            'uid' => $info['user_id'],
            'province_id' => $param['province_id'],
            'city_id' => $param['city_id'],
            'county_id' => $param['county_id'],
            'create_time' => time(),
            'address' => $param['address'],
            'status' => 2,
            'province_name' => $param['province_name'],
            'city_name' => $param['city_name'],
            'county_name' => $param['county_name'],
            'phone' => $param['phone'],
            'name' => $param['name']
        ];
        $userAddressModel->insert($data);
        $addressId = $userAddressModel->getLastInsID();
        $goodsOrderModel->where(['id' => $param['id']])->update([
            'address_id' => $addressId
        ]);
        return adminSuccess('修改成功');
    }

    public function completeGoodsOrder(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $goodsOrder = new GoodsOrder();
        $goodsInfo = $goodsOrder->where(['id' => $id, 'rand_code' => $param['rand_code']])->find();
        if (empty($goodsInfo)){
            return adminError('订单有误');
        }
        $goodsOrder->where(['id' => $id])->update(['status' => 6]);
        $userModel = new \app\home\model\User();
        $userInfo = $userModel->where(['id' => $goodsInfo['user_id']])->find();
        try {
            $userModel->startTrans();
            $amountLog = new AmountLog();
            $amountLog->where(['order_id' => $id,'order_sn' => $goodsInfo['sn_order']])
                ->update(['status' => 1,
                    'staff_id'=> $request->staff_account['id'],
                    'store_id' => $request->staff_account['store_id'],

                ]);
            if ($request->staff_account['store_id']> 0){
                $storeModel = new \app\merchant\model\Store();
                $storeModel->where(['id' => $request->staff_account['store_id']])->inc('goods_amount',$goodsInfo['reality_amount'])->update();
            }
            $integral = 0;
            $firstCommissionData = [];
            $secondCommissionData = [];
            if ($goodsInfo['total_price'] > $goodsInfo['point_deduction_amount']) { //积分全部抵扣了订单金额选择微信付款需要支付 0.01
                if ($goodsInfo['get_integral'] > 0) { //积分全部抵扣了订单金额选择微信付款需要支付 0.01
                    $integral = $goodsInfo['get_integral'];
                    $userAddIntegralData = [  // 添加用户积分
                        'mode_type' => 4,
                        'type' => 1,
                        'deduction_ratio' => $goodsInfo['get_integral_ratio'],
                        'num' => $integral,
                        'uid' => $userInfo['id'],
                        'create_time' => time(),
                        'order_id' => $goodsInfo['id']
                    ];
                    if ($userAddIntegralData['num'] > 0) {
                        $IntegralLogModel = new IntegralLog();
                        $IntegralLogModel->insert($userAddIntegralData);
                    }
                }
                $distribution_level = Config::getConfigValue('distribution_level');
                $firstCommissionData = [];
                $secondCommissionData = [];
                if ($distribution_level > 0) { // 分佣
                    if ($userInfo['pid'] > 0) {
                        $first_commission = Config::getConfigValue('first_commission');
                        $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                        if ($first_commission > 0) {
                            $userCommissionModel = new UserCommission();
                            $firstCommissionData = [
                                'trigger_uid' => $userInfo['id'],
                                'receive_uid' => $userInfo['pid'],
                                'level' => 1,
                                'amount' => bcdiv(bcmul($goodsInfo['reality_amount'], $first_commission, 2), 100, 2),
                                'ratio' => $first_commission,
                                'order_id' => $goodsInfo['id'],
                                'create_time' => time(),
                                'type' => 1,
                            ];
                            $userCommissionModel->insert($firstCommissionData);
                            $userModel->where(['id' => $userInfo['pid']])
                                ->inc('total_commission', bcdiv(bcmul($first_commission, $goodsInfo['reality_amount'], 2), 100, 2))
                                ->inc('surplus_commission', bcdiv(bcmul($first_commission, $goodsInfo['reality_amount'], 2), 100, 2))
                                ->update();
                        }
                        if ($distribution_level >= 2) {
                            $second_commission = Config::getConfigValue('second_commission');
                            if ($pUserInfo['pid'] > 0 && $second_commission > 0) {
                                $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                                $userCommissionModel = new UserCommission();
                                $secondCommissionData = [
                                    'trigger_uid' => $userInfo['id'],
                                    'receive_uid' => $pUserInfo['pid'],
                                    'level' => 2,
                                    'amount' => bcdiv(bcmul($goodsInfo['reality_amount'], $second_commission, 2), 100, 2),
                                    'ratio' => $second_commission,
                                    'order_id' => $goodsInfo['id'],
                                    'create_time' => time(),
                                    'type' => 1,
                                ];
                                $userCommissionModel->insert($secondCommissionData);
                                $userModel->where(['id' => $pUserInfo['pid']])
                                    ->inc('total_commission', bcdiv(bcmul($second_commission, $goodsInfo['reality_amount'], 2), 100, 2))
                                    ->inc('surplus_commission', bcdiv(bcmul($second_commission, $goodsInfo['reality_amount'], 2), 100, 2))
                                    ->update();
                            }
                        }
                    }
                }
            }
            $userModel->where(['id' => $userInfo['id']])
                ->inc('integral', $integral)
                ->inc('surplus_integral', $integral)
                ->inc('consumption_amount', $goodsInfo['reality_amount'])
                ->update();
            $userModel->updateUserLevel($userInfo['id'], bcadd($userInfo['consumption_amount'], $goodsInfo['reality_amount'], 2));
            $userModel->commit();
            $messageModel = new MessageTemplate();
            if ($integral > 0) {
                $messageModel->sendMessage($userInfo['openid'], [
                    'thing2' => '积分',
                    'amount8' => ['value' => $userAddIntegralData['num']],
                    'amount6' => ['value' => bcadd($userInfo['surplus_integral'], $userAddIntegralData['num'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')]], 'integral_add');

            }
            if ($firstCommissionData) { // 一级分佣
                $messageModel->sendMessage($pUserInfo['openid'], [
                    'thing2' => ['value' => '直推佣金'],
                    'amount8' => ['value' => $firstCommissionData['amount']],
                    'amount6' => ['value' => bcadd($pUserInfo['surplus_commission'], $firstCommissionData['amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
            }
            if ($secondCommissionData) { // 一级分佣
                $messageModel->sendMessage($ppUserInfo['openid'], [
                    'thing2' => ['value' => '间推佣金'],
                    'amount8' => ['value' => $secondCommissionData['amount']],
                    'amount6' => ['value' => bcadd($ppUserInfo['surplus_commission'], $secondCommissionData['amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')],
                ], 'commission_add'); //
            }

        } catch (Exception $exception) {
            $userModel->rollback();
            $goodsOrder->where(['id' => $id])->update(['status' => $goodsInfo['status']]);
            return adminError($exception->getMessage());
        }
        return success('操作成功');
    }

    public function confirmReturns(Request $request)
    {
        $param = $request->param();
        $id = $param['id'];
        $goodsOrder = new GoodsOrder();
        $return_order = getOrderNo('re');
        $userModel = new User();
        $goodsInfo = $goodsOrder->where(['id' => $id])->find();
        $userInfo = $userModel->where(['id' => $goodsInfo['user_id']])->find();
        $messageModel = new MessageTemplate();
        if ($goodsInfo['status'] == 5) {
            try {
                $goodsOrder->where(['id' => $id])->update(['status' => 9]);
                $goodsOrder->startTrans();
                if ($goodsInfo['pay_way'] == 2 && $goodsInfo['reality_amount'] > 0) {
                    $Offiaccount = new Offiaccount();
                    if ($goodsInfo['pay_destination'] == 2) {
                        $WechatInfo = $Offiaccount->wechatReturns($goodsInfo, $return_order);
                    } else {
                        $WechatInfo = $Offiaccount->mwechatReturns($goodsInfo, $return_order);
                    }
                    if ($WechatInfo['status'] == 'PROCESSING' || $WechatInfo['status'] == 'SUCCESS') {
                        $AmountLogData = [  // 金额扣除记录
                            'uid' => $goodsInfo['user_id'],
                            'amount' => $goodsInfo['reality_amount'],
                            'create_time' => time(),
                            'operate_type' => 18,
                            'pay_type' => 1,
                            'pay_method' => 1,
                            'order_id' => $id,
                            'ratio' => 1,
                            'type' => 1,
                            'order_sn' => $goodsInfo['sn_order'],
                        ];
                        $amountLogModel = new AmountLog();
                        $amountLogModel->insert($AmountLogData);
                    } else {
                        return adminError($WechatInfo['message']);
                    }
                }
                if ($goodsInfo['pay_way'] == 1) {
                    if ($goodsInfo['reality_amount'] > 0) {
                        $userModel->where(['id' => $goodsInfo['user_id']])
                            ->inc('balance', $goodsInfo['reality_amount'])
                            /*->dec('consumption_amount', $goodsInfo['reality_amount'])*/
                            ->update();
                        $AmountLogData = [  // 金额扣除记录
                            'uid' => $goodsInfo['user_id'],
                            'amount' => $goodsInfo['reality_amount'],
                            'create_time' => time(),
                            'operate_type' => 19,
                            'pay_type' => 4,
                            'pay_method' => 4,
                            'order_id' => $id,
                            'ratio' => 1,
                            'type' => 1,
                            'order_sn' => $goodsInfo['sn_order'],
                        ];
                        $amountLogModel = new AmountLog();
                        $amountLogModel->insert($AmountLogData);

                    }
                    if ($userInfo['phone']) {
                        $messageModel->sendAliMessage($userInfo['phone'], 'balance_add', [
                            'platform' => Config::getConfigValue('system_name'),
                            'name' => $goodsInfo['name'], [
                                'desc' => '订单退款',
                                'money' => $goodsInfo['reality_amount'],
                            ],

                        ]);;
                    }

                }
                if ($goodsInfo['user_coupon_id']) {
                    $userCouponModel = new UserCoupon();
                    $userCouponModel->where(['id' => $goodsInfo['user_coupon_id']])->update(['status' => 1]);
                    $userModel->where(['id' => $goodsInfo['user_id']])
                        ->inc('coupon_num')->update();
                }
                $point = bcmul($goodsInfo['point_deduction_amount'], $goodsInfo['point_deduction_ratio'], 2);
                $goodsOrder->where(['id' => $id])->update(['status' => 7]);
                if ($point > 0) {
                    $IntegralLogModel = new IntegralLog();
                    $userNeedIntegralData = [
                        'mode_type' => 7,
                        'type' => 1,
                        'deduction_ratio' => $goodsInfo['point_deduction_ratio'],
                        'num' => $point,
                        'uid' => $goodsInfo['user_id'],
                        'create_time' => time(),
                        'order_id' => $id
                    ];
                    $IntegralLogModel->insert($userNeedIntegralData);
                    $userModel->where(['id' => $goodsInfo['user_id']])->inc('surplus_integral', $point)->update();
                }
                $goodsOrder->commit();
            } catch (Exception $exception) {
                $goodsOrder->rollback();
                $goodsOrder->where(['id' => $id])->update(['status' => 5]);
                return adminError($exception->getMessage());
            }

            if ($goodsInfo['pay_way'] == 1 && $goodsInfo['reality_amount']) {
                $messageModel->sendMessage($userInfo['openid'], [
                    'character_string6' => ['value' => '退货返还余额'],
                    'amount8' => ['value' => $goodsInfo['reality_amount']],
                    'amount6' => ['value' => bcadd($userInfo['balance'], $goodsInfo['reality_amount'], 2)],
                    'time4' => ['value' => date('Y-m-d H:i')],
                ], 'balance_add'); //
            }
            return success('操作成功');
        }
    }

    public function withdrawalPass(Request $request)
    {
        $param = $request->param();
        $withdrawalModel = new \app\home\model\Withdrawal();
        $withdrawalInfo = $withdrawalModel->where(['id' => $param['id']])->find();
        $withdrawalInfo->where(['id' => $param['id']])->update(['status' => 2]);
        if ($withdrawalInfo['status'] != 1) {
            $withdrawalInfo->where(['id' => $param['id']])->update(['status' => $withdrawalInfo['status']]);
            return adminError('订单状态有误');
        }
        $userModel = new User();
        $userInfo = $userModel->where(['id' => $withdrawalInfo['uid']])->find();
        if ($withdrawalInfo['pay_mode'] == 1) {
            $offiaccount = new Offiaccount();
            $returnRequest = $offiaccount->withdrawal($userInfo['openid'], $withdrawalInfo);

            if (isset($returnRequest['batch_status']) && $returnRequest['batch_status'] != 'ACCEPTED' || $returnRequest['batch_status'] != 'PROCESSING') {
                $withdrawalModel->where(['id' => $param['id']])->update(['status' => 1]);
                return adminError('微信提示：', $returnRequest['message']);
            } else {
                $withdrawalModel->where(['id' => $param['id']])->update(['status' => 1]);
                return adminError('微信提示：', $returnRequest['message']);
            }
        }
        $withdrawalModel->where(['id' => $param['id']])->update(['status' => 3, 'update_time' => time()]);
        $userModel->where(['id' => $withdrawalInfo['uid']])->inc('withdrawn_balance', $withdrawalInfo['amount'])->update();
        $userCommissionModel = new UserCommission();
        $commissionData = [
            'trigger_uid' => $userInfo['id'],
            'receive_uid' => $userInfo['id'],
            'level' => 0,
            'amount' => bcmul($withdrawalInfo['amount'], $withdrawalInfo['ratio'], 2),
            'ratio' => $withdrawalInfo['ratio'],
            'order_id' => $withdrawalInfo['id'],
            'create_time' => time(),
            'type' => 3,
        ];
        if ($commissionData['amount'] > 0) {
            $userCommissionModel->insert($commissionData);
        }
        $messageModel = new MessageTemplate();
        $messageModel->sendMessage($userInfo['openid'], [
            'time7' => ['value' => date('Y-m-d H:i:s', $withdrawalInfo['create_time'])],
            'amount5' => ['value' => $withdrawalInfo['amount']],
            'short_thing6' => ['value' => $withdrawalInfo['fees']],
            'amount2' => ['value' => $withdrawalInfo['reality_amount']],
            'time3' => ['value' => date('Y-m-d  H:i:s')],

        ], 'withdrawal_success'); //
        return adminSuccess('成功');
    }


}